package swu.cx.myhttpjava;

import android.os.Handler;
import android.os.Looper;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

class JsonCallbackListener<T> implements CallbackListener {
    private Class<T> responseClass;
    private IJsonDataTransforListener listener;
    private Handler mHandler = new Handler(Looper.getMainLooper());
    public JsonCallbackListener(Class<T> responseClass,IJsonDataTransforListener listener){
        this.responseClass = responseClass;
        this.listener = listener;
    }
    @Override
    public void onSuccess(InputStream inputStream) {
            String response = getContent(inputStream);
            final T clazz = JSON.parseObject(response,responseClass);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    listener.onSuccess(clazz);
                }
            });

    }

    private String getContent(InputStream inputStream){
        StringBuilder builder = new StringBuilder();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String line = null;
            while (((line = reader.readLine()) != null)) {
                builder.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return builder.toString();
    }

    @Override
    public void onFailure() {

    }
}
